package com.lefu.es.system;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.lefu.es.blenew.helper.BleHelper1;
import com.lefu.es.blenew.utils.StringUtils1;
import com.lefu.es.constant.AppData;
import com.lefu.es.constant.UtilConstants;
import com.lefu.es.db.RecordDao;
import com.lefu.es.db2.MacDao;
import com.lefu.es.entity.DeviceMacDao;
import com.lefu.es.entity.Records;
import com.lefu.es.entity.UserModel;
import com.lefu.es.progressbar.NumberProgressBar;
import com.lefu.es.service.RecordService;
import com.lefu.es.service.UserService;
import com.lefu.es.util.LogUtil;
import com.lefu.es.util.MyUtil;
import com.lefu.es.util.SPUtil;
import com.lefu.es.util.SharedPreferencesUtil;
import com.lefu.es.util.StringUtils;
import com.lefu.es.util.ToastUtil;
import com.lefu.es.util.ToastUtils;
import com.lefu.es.util.UtilTooth;
import com.wellness.scale.R;

import java.util.List;

/**
 * 自动判断蓝牙4.0
 *
 * @author Leon
 */
@SuppressLint("HandlerLeak")
public class AutoBLEActivity extends BaseBleActivity {

    protected boolean isFirst = false;
    int count = 0;
    private boolean reCheck;
    private Button backButton;
    private Records receiveRecord = null;
    private RecordService recordService;
    private UserService userservice;
    private NumberProgressBar bnp;
    private String scaleType = null;
    private boolean isElectronic = false;
    /*** 是否已经返回*/
    private boolean isBack = false;
    /*** 点击事件 ***/
    private View.OnClickListener OnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            if (v.getId() == R.id.btn_mback) {
                backToUserEdit();
            }
        }
    };

    public void onClickBack(View v) {
        backToUserEdit();
    }

    /*** 蓝牙连接标记 ***/
    private boolean isConnected = false;
    /*** 显示提示语 ***/
    private int flagFrom;
    private TextView tv_pro;
    private TextView tv_unit;
    private Dialog receiveDataDialog;
    private Button cancelBtn;
    private Button saveBtn;
    private TextView textView1;
    private TextView textView2;
    private ImageView iv_point;
    /*** 超时检测线程 ***/
    private Runnable TimeoutRunnable = new Runnable() {
        public void run() {
            if (scaleType == null && !isBack && handler!=null) {
                    /*是否已经连接*/
                if (!isConnected) {
                    handler.sendEmptyMessage(3);
                } else {
                    /*更新进度为100*/
                    handler.sendEmptyMessage(4);
                }
                handler.postDelayed(this, 1000);
            }
        }
    };

    private List<DeviceMacDao> arrayList;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (!isBack) {
                        Intent intent0 = new Intent();
                        intent0.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent0.setClass(AutoBLEActivity.this, AutoBLEActivity.class);
                        startActivity(intent0);
                        stopPropertyAnim();
                        //finish();
                    }
                    break;
                case 2:
                    if (receiveDataDialog == null || !receiveDataDialog.isShowing()) {
                        LogUtil.e("connected and jump to LoadingActivity");
                        handler.removeCallbacks(TimeoutRunnable);
                        scanHandler.removeCallbacks(scanThread);
                        mScanner.stopScan();
                        showReceiveDataDialog(receiveRecord);
                    }
                    break;
                case 3:
                    if (bnp.getProgress() >= 100) {
                        bnp.setProgress(0);
                    }
                    bnp.incrementProgressBy(2);
                    break;
                case 4:
                    if (null != bnp) bnp.setProgress(100);
                    break;
                default:
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto);
        tv_pro = (TextView) findViewById(R.id.tv_pro);
        tv_unit = (TextView) findViewById(R.id.tv_danwei);
        isFirst = getIntent().getBooleanExtra("isfirst", false);
        flagFrom = getIntent().getIntExtra("flag_from", 0);
        iv_point = (ImageView) findViewById(R.id.imageView8);
        backButton = (Button) this.findViewById(R.id.btn_mback);
        backButton.setOnClickListener(OnClickListener);
        recordService = new RecordService(this);
        userservice = new UserService(this);
        Toast.makeText(AutoBLEActivity.this,
                getString(R.string.scale_keep_scale_work),
                Toast.LENGTH_SHORT).show();
        UtilConstants.su = new SharedPreferencesUtil(AutoBLEActivity.this);
		/*进度条*/
        bnp = (NumberProgressBar) findViewById(R.id.numberbar1);
		/* 启动超时线程*/
        new Thread(TimeoutRunnable).start();
		/*秤识别中*/
        AppData.isCheckScale = true;
		/*判断用户信息是否被清空*/
        if (UtilConstants.CURRENT_USER == null) {
            UtilConstants.CURRENT_USER = JSONObject.parseObject((String)
                    UtilConstants.su.readbackUp("lefuconfig", "addUser", ""), UserModel.class);
        }
        LogUtil.d("当前用户：" + UtilConstants.CURRENT_USER.toString());
        startPropertyAnim();
        //db = LitePal.getDatabase();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //stopScan();
        disConnect();
        if (handler!=null){
            handler.removeCallbacks(TimeoutRunnable);
            handler.removeCallbacks(null);
            handler.removeMessages(1);
            handler.removeMessages(2);
            handler.removeMessages(3);
            handler.removeMessages(4);
            handler = null;
        }
    }

   /* @Override
    protected void onDestroy() {
        super.onDestroy();
    }*/

    @Override
    public void updateConnectionState(int resourceId) {

    }

    @Override
    public void discoverBleService() {
        ToastUtils.ToastCenter(AutoBLEActivity.this, getString(R.string.scale_paired_success));
        //Health Scale
        isConnected = true;
        LogUtil.e("发送人体参数mDeviceName:" + mDeviceName);
        //发送人体参数
        if (null != mDeviceName && (mDeviceName.toLowerCase().startsWith("heal"))
                || null != mDeviceName
                && (mDeviceName.toLowerCase().startsWith("smart"))) {
            isElectronic = false;
            try {
                if (null != mBluetoothLeService) {
                    final BluetoothGattCharacteristic characteristic =
                            mBluetoothLeService.getCharacteristicNew(mBluetoothLeService.getSupportedGattServices(), "fff4");
                    mBluetoothLeService.setCharacteristicIndiacate(characteristic, true); //开始监听通道
                    String unit = "00";
                    //发送用户组数据
                    if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ST)) {
                        unit = "02";
                    } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)) {
                        unit = "01";
                    } else {
                        unit = "00";
                    }
                    // 获取用户组
                    String p = UtilConstants.CURRENT_USER.getGroup().replace("P", "0");
                    // 获取 校验位
                    String xor = Integer.toHexString(StringUtils.hexToTen("fd") ^ StringUtils.hexToTen("37") ^ StringUtils.hexToTen(unit) ^ StringUtils.hexToTen(p));
                    LogUtil.e("发送新称数据：" + "fd37" + unit + p + "000000000000" + xor);
                    // 发送数据
                    BleHelper1.getInstance().sendDateToScale(mBluetoothLeService, "fd37" + unit + p + "000000000000" + xor);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (mDeviceName != null && mDeviceName.toLowerCase().startsWith("yu")) {
            try {
                if (null != mBluetoothLeService) {
                    final BluetoothGattCharacteristic characteristic = mBluetoothLeService.getCharacteristicNew(mBluetoothLeService.getSupportedGattServices(), "2a9c");
                    mBluetoothLeService.setCharacteristicIndiacate(characteristic, true); //开始监听通道
                    //发送用户组数据
                    String unit = "00";
                    if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ST)) {
                        unit = "02";
                    } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)) {
                        unit = "01";
                    } else {
                        unit = "00";
                    }
                    // 获取用户组
                    String p = UtilConstants.CURRENT_USER.getGroup().replace("P", "0");
                    // 获取 校验位
                    String xor = Integer.toHexString(StringUtils.hexToTen("fd") ^ StringUtils.hexToTen("37") ^ StringUtils.hexToTen(unit) ^ StringUtils.hexToTen(p));
                    LogUtil.e( "发送新称数据：" + "fd37" + unit + p + "000000000000" + xor);
                    // 发送数据
                    BleHelper1.getInstance().sendDateToScale(mBluetoothLeService, "fd37" + unit + p + "000000000000" + xor);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String data = MyUtil.getUserInfo();
            LogUtil.e("富晶方案下发数据:" + data);
            BleHelper1.getInstance().sendDateToScale(mBluetoothLeService, data);
            isElectronic = true;
        }
    }

    private String lastReadMessage;
    @Override
    public void receiveBleData(String readMessage, String mac, String deviceName) {
        if (handler==null)  return;
        LogUtil.e("***readMessage-->" + readMessage + "***mac-->" + mac + "***deviceName-->"
                + deviceName + "***size-->"+readMessage.length());
        if (TextUtils.isEmpty(deviceName))  return;
        //双向通道
        if ((deviceName.equals("Electronic Scale")||isElectronic) && readMessage.length()==34){
            UtilConstants.CURRENT_SCALE = UtilConstants.BODY_SCALE;
            String lastStr = readMessage.substring(32,34);
            LogUtil.e("***lastStr-->" + lastStr);
            if (lastStr.equals("f1")){
                MyUtil.setProcessWeightAutoData0(AutoBLEActivity.this, readMessage.substring(0, 22),
                        tv_pro, tv_unit, UtilConstants.CURRENT_USER.getDanwei(), false);
            }else if (lastStr.equals("f0") && (TextUtils.isEmpty(lastReadMessage)||!lastReadMessage.equals(readMessage)) ){
                lastReadMessage = readMessage;
                receiveRecord = MyUtil.parseMessage(this.recordService, readMessage);
                if (null != receiveRecord) {
                    receiveRecord.setReceiveMsg(readMessage);
                }
                Message msg1 = handler.obtainMessage(2);
                msg1.obj = receiveRecord;
                handler.sendMessage(msg1);
                LogUtil.e("***锁定数据-->" + readMessage);
            }else{
                lastReadMessage = readMessage;
                receiveRecord = MyUtil.parseMessage(this.recordService, readMessage);
                if (null != receiveRecord) {
                    receiveRecord.setReceiveMsg(readMessage);
                }
                Message msg1 = handler.obtainMessage(2);
                msg1.obj = receiveRecord;
                handler.sendMessage(msg1);
                LogUtil.e("***锁定数据-->" + readMessage);
            }
            return;
        }

        /****兼容旧版本**起*/
        if (readMessage.startsWith("0306")) {
            LogUtil.e("**接下来收到的数据要兼容旧版本*readMessage**" + readMessage);
            UtilConstants.CURRENT_SCALE = UtilConstants.BODY_SCALE;
            UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
            Records record = MyUtil.parseZuKangMessage(this.recordService, readMessage, UtilConstants.CURRENT_USER);
            if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)
                    || UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_FATLB)
                    || UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ST)) {
                tv_pro.setText(UtilTooth.kgToLB_ForFatScale(record.getRweight()));
                tv_unit.setText("lb");
            } else {
                tv_pro.setText(UtilTooth.keep1Point3(record.getRweight()) + "");
                tv_unit.setText("kg");
            }
            if (receiveDataDialog == null || !receiveDataDialog.isShowing()) {
                LogUtil.e("*****接下来收到的数据****");
                receiveRecord = record;
                showReceiveDataDialog(record);
            }
            LogUtil.e( "**record**" + record);
            return;
        }
        /****兼容旧版本**终*/

        if (!TextUtils.isEmpty(mac)) {
            mDeviceAddress = mac;
        }
        if (!TextUtils.isEmpty(deviceName)) {
            mDeviceName = deviceName;
        }
        LogUtil.e("****检测读取到数据 readMessage-->" + readMessage);
        if (TextUtils.isEmpty(readMessage)) return;
        if (readMessage != null && readMessage.length() == 40) {
            readMessage = readMessage.substring(0, 22);
            LogUtil.e("****截取字符串后数据 readMessage-->" + readMessage);
        }
        LogUtil.e("****receiveBleData检测读取到数据 readMessage-->" + readMessage);
        if (readMessage.startsWith("cb") || readMessage.startsWith("ca")) {
            if (readMessage.length() == 22 && readMessage.startsWith("ca")) {
                mDeviceName = "Health Scale";
            }
        } else {
            if (UtilConstants.CURRENT_USER.getAgeYear() < 10 || UtilConstants.CURRENT_USER.getBheigth() < 100) {
                if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_KG)) {
                    Toast.makeText(AutoBLEActivity.this, getString(R.string.age_error_4), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(AutoBLEActivity.this, getString(R.string.age_error_6), Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }

        boolean newScale = false;
        try {
            if ((readMessage.startsWith("0306"))) {//阿里秤
                newScale = true;
                UtilConstants.CURRENT_SCALE = UtilConstants.BODY_SCALE;
            } else {
                newScale = false;
                //测脂错误
                if (readMessage.startsWith("cb") || readMessage.startsWith("ca")) {

                } else {
                    //测脂错误
                    if (readMessage.equals(UtilConstants.ERROR_CODE)) {
                        if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ST)
                                || UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)) {
                            Toast.makeText(AutoBLEActivity.this, getString(R.string.user_data_error_lb), Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(AutoBLEActivity.this, getString(R.string.user_data_error), Toast.LENGTH_LONG).show();
                        }
                        return;
                    } else if (readMessage.equals(UtilConstants.ERROR_CODE_TEST)) {
                        Toast.makeText(AutoBLEActivity.this, getString(R.string.scale_measurement_error), Toast.LENGTH_LONG).show();
                        return;
                    }
                }

                /** 称类型判断 */
                String choice_scale = "";
                if ((readMessage.toLowerCase().startsWith(UtilConstants.BODY_SCALE))) {
                    choice_scale = UtilConstants.BODY_SCALE;
                } else if ((readMessage.toLowerCase().startsWith(UtilConstants.BATHROOM_SCALE))) {
                    choice_scale = UtilConstants.BATHROOM_SCALE;
                } else if ((readMessage.toLowerCase().startsWith(UtilConstants.BABY_SCALE))) {
                    choice_scale = UtilConstants.BABY_SCALE;
                } else if ((readMessage.toLowerCase().startsWith(UtilConstants.KITCHEN_SCALE))) {
                    choice_scale = UtilConstants.KITCHEN_SCALE;
                }
                UtilConstants.CURRENT_SCALE = choice_scale;
            }
            if (null != mDeviceName && mDeviceName.toLowerCase().startsWith("smart")
                    || (null != mDeviceName && mDeviceName.toLowerCase().startsWith("heal")
                    || (null != mDeviceName && mDeviceName.equals(AppData.LF_SCALE)) && readMessage.length() == 22)) {
                //新的DL Scale
                //CF 88 13 00 14 00 00 00 00 00 40
                if (RecordDao.isLockData(readMessage)) {
                    if (!RecordDao.checkData(readMessage)) return;
                    if ((System.currentTimeMillis() - UtilConstants.receiveDataTime > 1000)) {
                        UtilConstants.receiveDataTime = System.currentTimeMillis();
                        /*是否是重新检测*/
                        Boolean reCheck = (Boolean) UtilConstants.su.readbackUp("lefuconfig", "reCheck", false);
                        UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
                        receiveRecord = RecordDao.parseDLScaleMeaageNotSave(recordService, readMessage, UtilConstants.CURRENT_USER);
                        handler.sendEmptyMessage(2);
                    }
                } else {
                    LogUtil.e("******合泰方案过程数据处理******");
                    healthData(readMessage);
                }
            } else {
                LogUtil.e("******富晶方案的数据 readMessage-->" + readMessage);
                /**判断是不是两次连续的数据*/
                if (readMessage.length() > 31 && (System.currentTimeMillis() - UtilConstants.receiveDataTime > 1000)) {
                    UtilConstants.receiveDataTime = System.currentTimeMillis();
                    scaleType = UtilConstants.CURRENT_SCALE;
                    UtilConstants.su.editSharedPreferences("lefuconfig", "scale", UtilConstants.CURRENT_SCALE);
                    /*是否是重新检测*/
                    reCheck = (Boolean) UtilConstants.su.readbackUp("lefuconfig", "reCheck", false);
                    LogUtil.e("******reCheck readMessage-->" + reCheck);
                    UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
                    if (readMessage.toLowerCase().startsWith(UtilConstants.KITCHEN_SCALE)) {
                        LogUtil.e("******富晶方案数据3******");
                        receiveRecord = RecordDao.dueKitchenDate1(recordService, readMessage, null);
                    } else {
                        if (newScale) {
                            UtilConstants.CURRENT_USER.setScaleType(UtilConstants.BODY_SCALE);
                            LogUtil.e("******富晶方案数据1 readMessage-->" + readMessage);
                            receiveRecord = RecordDao.parseZuKangMeaage(recordService, readMessage, UtilConstants.CURRENT_USER);
                        } else {
                            LogUtil.e("******富晶方案数据2 readMessage-->" + readMessage);
                            receiveRecord = RecordDao.dueDate1(recordService, readMessage);
                        }
                    }
                    receiveRecord.setUseId(UtilConstants.CURRENT_USER.getId());
                    receiveRecord.setUgroup(UtilConstants.CURRENT_USER.getGroup());
                    LogUtil.e("******receiveRecord readMessage-->" + receiveRecord.toString());
                    handler.sendEmptyMessage(2);
                }
            }
        } catch (Exception e) {
            LogUtil.e("****解析数据异常-->" + e.getMessage());
        }
    }

    @Override
    protected void saveDataCallBack(Records records) {

    }

    /*** 接收到数据提示 ***/
    protected void showReceiveDataDialog(Records record) {
        if (record == null) return;
        // 初始化自定义布局参数
        LogUtil.e("***接收到数据提示-->" + record.toString());
        LayoutInflater layoutInflater = getLayoutInflater();
        // 为了能在下面的OnClickListener中获取布局上组件的数据，必须定义为final类型.
        View customLayout = layoutInflater.inflate(R.layout.activity_receive_alert2,
                (ViewGroup) findViewById(R.id.receiveDataDialog));
        cancelBtn = (Button) customLayout.findViewById(R.id.cancle_datacbtn);
        saveBtn = (Button) customLayout.findViewById(R.id.save_databtn);
        textView1 = (TextView) customLayout.findViewById(R.id.textView1);
        textView2 = (TextView) customLayout.findViewById(R.id.textView2);
        String danwei = StringUtils.getDanWei(record.getUnitType());
        if (record != null && record.getScaleType().equals("cf")) {
            textView1.setText(R.string.faxian_fat_scale);
            if ("kg".equals(danwei)) {
                textView2.setText(getString(R.string.bind_fat_tishi) + record.getRweight() + "kg" + "？");
            } else if ("lb".equals(danwei)) {
                textView2.setText(getString(R.string.bind_fat_tishi) + UtilTooth.kgToLB(record.getRweight()) + "lb" + "？");
            }
        } else if (record != null && record.getScaleType().equals("ce")) {
            textView1.setText(R.string.faxian_ce_scale);
            if ("kg".equals(danwei)) {
                textView2.setText(getString(R.string.bind_ce_tishi) + record.getRweight() + "kg？");
            } else {
                textView2.setText(getString(R.string.bind_ce_tishi) + UtilTooth.kgToLB(record.getRweight()) + "lb？");
            }
        } else if (record != null && record.getScaleType().equals("cb")) {
            LogUtil.e( "发现的是婴儿秤数据");
            textView1.setText(R.string.faxian_cb_scale);
            if ("kg".equals(danwei)) {
                textView2.setText(getString(R.string.bind_cb_tishi) + record.getRweight() + "kg？");
            } else {
                textView2.setText(getString(R.string.bind_cb_tishi) + UtilTooth.kgToLB(record.getRweight()) + "lb？");
            }

        } else if (record != null && record.getScaleType().equals("ca")) {
            LogUtil.d("****发现的是营养秤数据***");
            textView1.setText(R.string.faxian_ca_scale);
        }
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.d("取消");
                // scanHandler.removeCallbacks(scanThread);
                receiveDataDialog.dismiss();
                if (null != mScanner) {
                    //  mScanner.stopScan();
                }
                if (null != mBluetoothLeService) {
                    mBluetoothLeService.disconnect();
                }
                mActivty = true;
                startScanBLE();
                isConnected = false;
            }
        });
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.d("*****是-->" + receiveRecord.toString());
                long date = System.currentTimeMillis();
                SPUtil.put(AutoBLEActivity.this, "dialogdate", date + "");
                saveUser();
                arrayList = StringUtils1.getBindDeviceMac();
                if (arrayList.isEmpty()) {
                    LogUtil.e( "当前没有绑定mac");
                    LogUtil.e( "当前的秤类型是：" + UtilConstants.CURRENT_USER.getScaleType());
                    if ("cf".equals(UtilConstants.CURRENT_USER.getScaleType())) {
                        bindScale("2");
                    } else if ("ce".equals(UtilConstants.CURRENT_USER.getScaleType())) {
                        bindScale("1");
                    } else if ("ca".equals(UtilConstants.CURRENT_USER.getScaleType())) {
                        bindScale("3");
                    } else if ("cb".equals(UtilConstants.CURRENT_USER.getScaleType())){
                        bindScale("4");
                    }
                } else {
                    LogUtil.d( "当前没有绑定mac");
                    LogUtil.d( "当前的秤类型是：" + UtilConstants.CURRENT_USER.getScaleType());
                    if ("cf".equals(UtilConstants.CURRENT_USER.getScaleType())) {
                        bindScale("2");
                    } else if ("ce".equals(UtilConstants.CURRENT_USER.getScaleType())) {
                        bindScale("1");
                    } else if ("ca".equals(UtilConstants.CURRENT_USER.getScaleType())) {
                        bindScale("3");
                    } else if ("cb".equals(UtilConstants.CURRENT_USER.getScaleType())){
                        bindScale("4");
                    }
                }
                /*Intent intent = new Intent(AutoBLEActivity.this, LoadingActivity.class);
                startActivity(intent);
                finish();*/
            }
        });

        receiveDataDialog = new Dialog(AutoBLEActivity.this, R.style.dialog);
        receiveDataDialog.setContentView(customLayout);
        receiveDataDialog.show();
        Window window = receiveDataDialog.getWindow();
        window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置
        window.setWindowAnimations(R.style.mystyle); // 添加动画
    }

    /*** 对合泰方案秤的数据进行处理 ***/
    private void healthData(String readMessage) {
        if (count > 1) {
            return;
        }
        if (readMessage.startsWith("ca") && readMessage.length() == 22) {
            count++;
            LogUtil.d("====count==" + count);
            if (count > 5) {
            } else {
                healthDataSkip(readMessage);
            }
        } else {
            LogUtil.d( "对合泰方案秤的数据进行处理");
            MyUtil.setProcessWeightData6(AutoBLEActivity.this, readMessage, tv_pro, tv_unit, null, false);
        }
    }

    private void saveUser() {
        LogUtil.d("===saveUser:" + UtilConstants.CURRENT_USER.toString());
        if (flagFrom == 1) {
            /*更新用户信息*/
            LogUtil.d( "修改用户信息>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            try {
                UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
                UtilConstants.SELECT_USER = UtilConstants.CURRENT_USER.getId();
                userservice.update(UtilConstants.CURRENT_USER);
                UtilConstants.su.editSharedPreferences("lefuconfig", "user", UtilConstants.SELECT_USER);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            /*添加用户信息*/
            try {
                UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
                LogUtil.d( " 添加用户信息：" + UtilConstants.CURRENT_USER.toString());
                // UtilConstants.SELECT_USER = UtilConstants.CURRENT_USER.getId();
                int id = userservice.save(UtilConstants.CURRENT_USER);
                LogUtil.d( "====id:" + id);
                UtilConstants.SELECT_USER = id;
                UtilConstants.su.editSharedPreferences("lefuconfig", "user", id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        /*保存蓝牙类型*/
        UtilConstants.su.editSharedPreferences("lefuconfig", "bluetooth_type" + UtilConstants.CURRENT_USER.getId(), "BLE");
        if (receiveRecord != null && receiveRecord.getRweight() > 0) {
            saveData(receiveRecord);
        }
    }

    private void bindScale(final String type) {
        LogUtil.e("****mac_address>-->" + mDeviceAddress);
        /**保存蓝牙数据实体类***/
        DeviceMacDao deviceMacDao = new DeviceMacDao();
        deviceMacDao.setDeviceName(mDeviceName);
        deviceMacDao.setDeviceType(type);
        deviceMacDao.setMac(mDeviceAddress);
        MacDao.insertMac(deviceMacDao);
        /***数据库查询所有据***/
        arrayList = MacDao.queryAll();
        for (int i = 0; i < arrayList.size(); i++) {
            if (!TextUtils.isEmpty(deviceMacDao.getMac())) {
                ToastUtil.show(this, getResources().getString(R.string.bind_scucess));
                //stopBle();
                Intent intent = new Intent(AutoBLEActivity.this, LoadingActivity.class);
                startActivity(intent);
                stopPropertyAnim();
                //finish();
                break;
            }
        }
    }

    /*** 对只有广播数据的营养秤的页面跳转 ***/
    private void healthDataSkip(String readMessage) {
        LogUtil.d("对只有广播数据的营养秤的页面跳转");
        /*是否是重新检测*/
        Boolean reCheck = (Boolean) UtilConstants.su.readbackUp("lefuconfig", "reCheck", false);
        UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
        /*保存蓝牙类型*/
        UtilConstants.su.editSharedPreferences("lefuconfig", "bluetooth_type" + UtilConstants.CURRENT_USER.getId(), "BLE");
        receiveRecord = RecordDao.parseDLScaleMeaageNotSave(recordService, readMessage, UtilConstants.CURRENT_USER);
        handler.sendEmptyMessage(2);
    }

    private void saveData(Records records) {
        if (records != null) {
            LogUtil.d("UtilConstants.CURRENT_USER.getRroup" + UtilConstants.CURRENT_USER.getGroup());
            records.setUseId(UtilConstants.SELECT_USER);
        }
        LogUtil.d("保存测量数据：" + records.toString());
        if (recordService != null) {
            recordService.saveOneRecord(records);
        }
    }

    private Animation animation;
    private void startPropertyAnim() {
        animation = new RotateAnimation(0, 359,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(2000);
        animation.setRepeatCount(-1);
        animation.setFillAfter(false);
        animation.setInterpolator(new LinearInterpolator());
        iv_point.setLayerType(View.LAYER_TYPE_HARDWARE,null);
        iv_point.startAnimation(animation);
    }

    private void stopPropertyAnim(){
        if (animation!=null){
            animation.cancel();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backToUserEdit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /*** 返回到个人信息编辑界面 ***/
    private void backToUserEdit() {
        try {
            isBack = true;
            if (null != mScanner) {
                mScanner.stopScan();
            }
            if (null != mBluetoothLeService) {
                mBluetoothLeService.disconnect();
            }
            finish();
            //**是否是重新检测*//*
            reCheck = (Boolean) UtilConstants.su.readbackUp("lefuconfig", "reCheck", false);
            //*结束程序*//*
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
